<?php 
require_once "../config.php";
require_once "../functions.php";
/**
 * 1.获取分类的id,第几次获取数据，一共获取多少条
 * 2 到数据库中查找对应的数据
 * 3.把数据返回给前台，让其生成结构
 * 
*/

//1. 获取必要的参数
$categoryId = $_POST['categoryId'];
$currentPage = $_POST['currentPage'];
$pageSize = $_POST['pageSize'];
//1.2 计算出要从哪里开始获取
$offset = ($currentPage - 1)*$pageSize;
//2.查询数据库
//2.1 连接数据库
$connect = connect();
//2.2 sql语句
$sql = "select p.id,p.title,p.created,p.content,p.views,p.likes,p.feature,u.nickname,c.name,(select count(id) from comments where comments.post_id = p.id) as commentsCount from posts p left join users u on u.id = p.user_id left join categories c on c.id = p.category_id where p.category_id = {$categoryId} limit {$offset},{$pageSize};";
//2.3 执行查询
$postArr = query($connect,$sql);
//3.返回数据

/**
 * {
 *  'code':请求的状态, - 约定1代表成功 0代表失败
 *  'msg':想要返回给前台的数据
 * }
 * 
 */

//还得计算出所有的文章总共可以获取多少次，返回给前台让其判断加载更多是否应该显示给用户
$sql = "select count(id) as postsCount from posts where category_id = {$categoryId}";
$countArr = query($connect,$sql);
$pageCount = $countArr[0]['postsCount'];
//因为查询结果是二维数组
// print_r($countArr);
$response = ["code"=>0,"msg"=>"操作失败"];
//3.返回数据
if($postArr){
    $response['code'] = 1;
    $response['msg'] = '操作成功';
    $response['data'] = $postArr;
    $response['pageCount'] = $pageCount;
}
echo json_encode($response);
?>